package com.company;

import java.io.File;
import java.io.FileInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class UDP_File_Sender {

    public static void main(String[] args) throws Exception{
        DatagramSocket ds = new DatagramSocket(8888);
        InetAddress address = InetAddress.getByName("192.168.31.120");
        int port1 = 5545;
        int port2 = 9899;
        while(true) {
            System.out.println("请输入要发送的文件的绝对路径");
            Scanner sc = new Scanner(System.in);
            String path = sc.next();

            if(path.equals("Exit"))
                break;
            File file = new File(path);
            while(!file.exists())
            {
                System.out.println("该路径文件不存在，请重新输入：");
                path = sc.next();
                file = new File(path);
            }
            FileInputStream fis = new FileInputStream(file);
            byte[] buf = new byte[1024];
            int len;
            System.out.println("向服务端传输文件中……");
            String fileName = file.getName();
            byte[] name = fileName.getBytes();
            DatagramPacket dp = new DatagramPacket(name,name.length,address,port1);
            ds.send(dp);
            while((len = fis.read(buf)) != -1) {
                dp = new DatagramPacket(buf, len, address, port2);
                ds.send(dp);
            }
            byte[] end = new byte[0];
            dp = new DatagramPacket(end,end.length,address,port2);
            ds.send(dp);
            System.out.println("向" + address.getHostAddress() + ":" + port2 + "发送文件" + fileName + "完毕！");
            fis.close();
        }
        ds.close();
        System.out.println("程序退出");
    }
}